#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
main function：主要实现把txt中的每行数据写入到excel中,先把两个国际化字符串文件转为txt文本文件，然后一一对照，写入Excel 中
'''
 
#################
#

import xlwt #写入文件
import xlrd #打开excel文件
import os
import sys

# 切换到文件当前目录
os.chdir(sys.path[0])

def languageString(key,lines):
    language_string = ''
    for line in lines:
        if '=' in line:
            zh_key = line.split('=')[0].strip()
            if key == zh_key:
                language_string = line.split('=')[1].strip()
                break;

    print(language_string)
    return language_string;

def getStingsPath(sheet):

    enFileLines = ''
    fileLinesList = []
    logsPath = 'Excel/log.txt'
    if os.path.exists(logsPath):
        with open(logsPath, 'r') as f:

            sheet.write(0, 0, "key")
            column = 1

            for line in f.readlines():
                stringPath = line.strip()
                if os.path.exists(stringPath):
                    sheet.write(0, column, os.path.splitext(stringPath.split("/")[-2])[0])
                    column = column + 1
                    if stringPath.__contains__('en'):
                        with open(stringPath, 'r') as f:
                            enFileLines = f.readlines()
                    else:
                        with open(stringPath, 'r') as f:
                            fileLinesList.append(f.readlines())

    if enFileLines != '':
        fileLinesList.insert(0,enFileLines)
    return fileLinesList



def string_to_excel(excelName):
    # 以下路径改为自己相应的路径
    #新建一个excel文件
    file=xlwt.Workbook(encoding='utf-8',style_compression=0)
    #新建一个sheet
    sheet=file.add_sheet('data')

    fileHandleList = getStingsPath(sheet)

    if len(fileHandleList) > 0:
        row = 1
        for line in fileHandleList[0]:
            if ('=' in line):
                key = line.split('=')[0].strip()
                # value = line.split('=')[1].strip()
                sheet.write(row,0,key)

                column = 1
                for lines in fileHandleList:
                    sheet.write(row, column, languageString(key,lines))
                    column = column + 1

                row = row + 1

    file.save(excelName)


if __name__ == "__main__":
    # 从字符串文件导出到excel
    string_to_excel('Excel/v4.2翻译（中英西）.xls')